﻿@{
    ViewBag.Title = "Notifications";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (User != null)    
{
    
    <h2 class="centeredHeaderText">My notifications</h2>
    <div id="PresentationBox">
        <table class="DataPresentationtable" id="myNotifications">
            <tr>
                <td><center><img src="/Content/images/loading.gif" />loading notifications...</center></td>
            </tr>
        </table>
    </div>

    <script type="text/javascript">

    var dataSet = [];
    var activateLink = '@Url.Action("ActivateAccount", "Authentification")';
    var denyLink = '@Url.Action("DenyAccount", "Authentification")';
    var removeNotificationLink = '@Url.Action("RemoveNotification", "Notification")';

    function activateAccount(userId, messageId) {
        $.get(activateLink + "/" + userId + "?msgId=" + messageId, function (data) {
            if (data == "True") {
                setHttpMessage("Account activated", true);
                location.reload();
            }
            else {
                setHttpMessageDynamic("Account could not be activated due to technical problems. Please try again later.", false);
            }
        });
    }

    function disallowAccount(userId, messageId) {
        $.get(denyLink + "/" + userId + "?msgId=" + messageId, function (data) {
            if (data == "True") {
                setHttpMessage("Account deleted", true);
                location.reload();
            }
            else {
                setHttpMessageDynamic("Account could not be deleted due to technical problems. Please try again later.", false);
            }
        });
    }

    function allowRenewRequest(userId, notificationId) {
        $.ajax({
            url: "/api/user/" + userId + "/?renewExpireDate",
            type: "POST",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
            }
        }).done(function () {
            removeNotification(notificationId, false);
        }).fail(function () {
            setHttpMessageDynamic("Request could not be accepted. Please try again.", false);
        }).always(function (data) {
            console.log(data);
        });
    }

    function removeNotification(notificationId, showMessages) {
        $.ajax({
            url: "/api/notification/" + notificationId,
            type: "DELETE",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
            }
        }).done(function () {
            if (showMessages) {
                setHttpMessage("Notification removed", true);
            }
            location.reload();
        }).fail(function () {
            if (showMessages) {
                setHttpMessageDynamic("Notification could not be deleted.", false);
            }
        }).always(function (data) {
            console.log(data);
        });
    }

    function markMessageAsRead(notificationId) {
        $.ajax({
            url: "/api/notification/" + notificationId + "?read=true",
            type: "PUT",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
            }
        }).done(function () {
            console.log("notification marked as read (" + notificationId + ")");
        }).fail(function () {
            console.log("notification could not be marked as read (" + notificationId + ")");
        });
    }

    $(document).ready(function () {
        $.ajax({
            url: "/api/notification/",
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
            },
            dataType: "json"
        }).done(function (data) {
            console.log("got notifications");
            console.log(data);

            $.each(data, function (key, val) {
                console.log(val);

                var message = [];
                //title.Title = val.Title.BookTitle;
                message.Sender = (val.Sender == null) ? "System" : val.Sender.FirstName + " " + val.Sender.LastName;

                message.Message = val.Message;

                var sendDate = new Date(val.SendDate.replace("T", " ").split(".").splice(0, 1));
                console.log(sendDate);
                message.Date = sendDate.toLocaleString();

                console.log(val.Type);
                if (val.Type == 0) {
                    message.Action = "<a href='javascript:activateAccount(" + val.Sender.UserId + ", " + val.NotificationId + ")'>allow</a>";
                    message.Action += " / <a href='javascript:disallowAccount(" + val.Sender.UserId + ", " + val.NotificationId + ")'>deny</a>";
                } else if (val.Type == 5) {
                    message.Action = "<a href='javascript:allowRenewRequest(" + val.Sender.UserId + ", " + val.NotificationId + ")'>allow</a>";
                    message.Action += " / <a href='javascript:removeNotification(" + val.NotificationId + ", true)'>remove</a>";
                }
                else
                    message.Action = "<a href='javascript:removeNotification(" + val.NotificationId + ", true)'>remove</a>";

                if (!val.Read) {
                    console.log("notification is unread. mark is as read");

                    message.Message = "<b><i>" + message.Message + "</i></b>";

                    markMessageAsRead(val.NotificationId);
                }

                dataSet.push(message);
            });

            $('#myNotifications').DataTable({
                "bFilter": false,
                "fnDrawCallback": function () {
                    if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
                        $('#myNotifications_paginate').css("display", "block");
                    } else {
                        $('#myNotifications_paginate').css("display", "none");
                    }
                },
                "order": [[1, "desc"]],
                "data": dataSet,
                "columns": [
                    { "data": "Sender", "title": "Sender", "sWidth": "20%" },
                    { "data": "Date", "title": "Send date", "sWidth": "20%" },
                    { "data": "Message", "title": "Message", "sWidth": "40%" },
                    { "data": "Action", "title": "Action", "sWidth": "20%" },
                ]
            });

            //remove ugly DataTable css
            $('#myNotifications').removeClass("dataTable");

        }).fail(function (data) {
            console.log("could not get notifications");
            console.log(data);
        });
    });
    </script>
}